package cn.lijiajia3515.cairo.system.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

@EnableCaching
@Configuration
@Slf4j
public class CacheConfig {

	@Component
	public static class CairoCacheConfigurer implements CachingConfigurer {
		private final CacheManager cacheManager;

		public CairoCacheConfigurer(CacheManager cacheManager) {
			this.cacheManager = cacheManager;
		}

		@Override
		public CacheManager cacheManager() {
			return cacheManager;
		}

		@Override
		public CacheResolver cacheResolver() {
			return new SimpleCacheResolver(cacheManager);
		}

		@Override
		public KeyGenerator keyGenerator() {
			return new SimpleKeyGenerator();
		}

		@Override
		public CacheErrorHandler errorHandler() {
			return new SimpleCacheErrorHandler();
		}
	}

	@Bean
	public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties, @Qualifier("objectValueRedisSerializer") RedisSerializer<?> valueRedisSerializer) {
		CacheProperties.Redis redisProperties = cacheProperties.getRedis();
		RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
		config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueRedisSerializer));
		if (redisProperties.getTimeToLive() != null) {
			config = config.entryTtl(redisProperties.getTimeToLive());
		}
		if (redisProperties.getKeyPrefix() != null) {
			config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
		}
		if (!redisProperties.isCacheNullValues()) {
			config = config.disableCachingNullValues();
		}
		if (!redisProperties.isUseKeyPrefix()) {
			config = config.disableKeyPrefix();
		}
		return config;
	}
}
